/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef CONCURRENT_TASK_SERVICES_CONCURRENTSEVICE_INCLUDE_CONCURRENT_TASK_CONTROLLER_H
#define CONCURRENT_TASK_SERVICES_CONCURRENTSEVICE_INCLUDE_CONCURRENT_TASK_CONTROLLER_H

#include "single_instance.h"
#include <unordered_set>
#include <list>
#include <unordered_map>
#include "concurrent_task_type.h"
#include "qos_manager.h"
#include "json/json.h"

namespace OHOS {
namespace ConcurrentTask {

class ForegroundAppRecord;

class TaskController {
    DECLARE_SINGLE_INSTANCE(TaskController);

public:
    void ReportData(uint32_t resType, int64_t value = 0, const Json::Value& payload = nullptr);
    void QueryInterval(int queryItem, IntervalReply& queryRs);
    void Init();

private:
    bool CheckUid(pid_t uid);
    void TypeMapInit();
    void QosApplyInit();
    void TryCreateRsGroup();
    void QueryUi(pid_t uid, IntervalReply& queryRs);
    void QueryRender(pid_t uid, IntervalReply& queryRs);
    void QueryRenderService(pid_t uid, IntervalReply& queryRs);
    void QueryHwc(pid_t uid, IntervalReply& queryRs);
    int GetRequestType(std::string strRequstType);
    void DealSystemRequest(int requestType, const Json::Value& payload);
    void DealAppRequest(int requestType, const Json::Value& payload, pid_t uid);
    void NewForeground(int uid);
    void NewBackground(int uid);
    void NewAppStart(int uid);
    void AppKilled(int uid);
    std::list<ForegroundAppRecord>::iterator GetRecordOfUid(int uid);
    void PrintInfo();
    std::list<ForegroundAppRecord> m_foregroundApp = {};
    std::unordered_map<std::string, int> m_MsgType = {};
    QosManager m_qosManager;
    std::vector<int> m_authApps;
    int m_renderServiceGrp = -1;
    bool m_rtgEnabled = false;
};

class ForegroundAppRecord {
public:
    ForegroundAppRecord(int uid);
    ~ForegroundAppRecord();

    void AddKeyThread(int tid, int prio = PRIO_NORMAL);
    void DeleteKeyThread(int tid);
    bool BeginScene();
    bool EndScene();
    int GetUid();
    int GetGrpId();
    bool IsValid();
    void PrintKeyThreads();
private:
    int m_uid = 0;
    int m_grpid = 0;
    std::unordered_set<int> m_keyThreads;
};

} // namespace ConcurrentTask
} // namespace OHOS

#endif // CONCURRENT_TASK_SERVICES_CONCURRENTSEVICE_INCLUDE_CONCURRENT_TASK_CONTROLLER_H